﻿using System;
using System.Collections.Generic;
using System.IO;
using CompactMapper.Orm.Contracts;
using CompactMapper.Orm.UnitOfWork.Mappings;
using CompactMapper.Orm.Util;

namespace CompactMapper.Orm.UnitOfWork
{
    public class UnitOfWorkFactory
    {
        //Static to speed up unit tests
        private static IMappings _mappings;
        private readonly String _connectionString;

        public String ConnectionString { get { return _connectionString; } }
        public static IMappings Mappings
        {
            get { return _mappings; }
        }


        public ConnectionFactory.ConnectionWrapper CreateConnection()
        {
            return ConnectionFactory.CreateConnection(_connectionString);
        }

        public UnitOfWorkFactory(IEnumerable<String> assemblyStrings, String connectionString)
        {
            if (Mappings == null)
            {
                using (new TimedTrace("Creating Mappings"))
                    _mappings = new Mappings.Mappings(assemblyStrings);
            }
            _connectionString = connectionString;
            ConnectionFactory.Reset();
            using (new TimedTrace("Creating Database"))
                DatabaseCreation.CreateDatabase(_connectionString, Mappings);
        }

        public IKeyedSqLiteUnitOfWork<T> GetKeyedUnitOfWork<T>() where T : class, IKeyedPersistent
        {
            return new SqLiteKeyedUnitOfWork<T>(_connectionString, _mappings);
        }
        public IKeyedSqLiteUnitOfWork<T> GetKeyedUnitOfWork<T>(IMappings mappings) where T : class, IKeyedPersistent
        {
            return new SqLiteKeyedUnitOfWork<T>(_connectionString, mappings);
        }


        public void DumpSchema(String path)
        {
            using (var sourceStream = Mappings.DumpSchema())
            using (var reader = new StreamReader(sourceStream))
            using (var outputStream = new FileStream(path, FileMode.Create))
            using (var writer = new StreamWriter(outputStream))
                writer.Write(reader.ReadToEnd());
        }
    }
}